import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
import { global } from '@/utils/status';
import useAppStore from '@/stores/app';
import * as storage from '@/utils/storage';
import * as userApi from '@/api/user';
import * as status from '@/utils/status';
import * as Router from '@/router/index';
import { deepCopy } from '@/utils/utils';

const useUserStore = defineStore('user', () => {
  const token = ref(storage.getToken());
  const userId = ref(storage.getUserId());
  const userInfo = ref(JSON.parse(storage.getUserInfo()));
  const role = ref(storage.getRole());
  const currentRoutes = ref(JSON.parse(storage.getRoutes()));
  const currentModal = ref(storage.getModal());
  const currentModalTitle = ref(storage.getModalTitle());
  const isLogin = computed(() => {
    return !!token.value;
  })
  // 用户登录
  function login(loginForm){
    return new Promise((resolve, reject) => {
      userApi.login(loginForm)
        .then(async (res) => {
          if (res.token){
            token.value = res.token;
            storage.setToken(res.token);
            await getCurrentUserInfo();
            resolve();
          }
        })
        .catch(err => {
          console.log(err)
          reject(err.message || '登录失败请稍后重试');
        })
    });
  }
  // 获取用户信息
  function getCurrentUserInfo(){
    return new Promise((resolve, reject) => {
      userApi.getCurrentUserInfo()
        .then(res => {
          // console.log('用户信息getUserInfo')
          // console.log(res)
          if (!res){
            reject('系统未返回用户信息，请稍后重试');
            return;
          }
          const { user } = res;
          let { modalCode, modalDos } = user;
          modalCode = modalCode ? modalCode : global.modal.IMAGE;
          let modalTitle = modalDos.find(item => item.modalCode === modalCode)?.modalName;
          userInfo.value = user;
          userId.value = user.userId;
          currentModal.value = modalCode;
          currentModalTitle.value = modalTitle;
          // 正常请求获取role
          if (typeof user.roleKeys === 'string' && user.roleKeys !== ''){
            role.value = user.roleKeys;
            setCurrentRoutes(user.roleKeys);
            storage.setRole(user.roleKeys);
          } else {
            role.value = global.roles.ADMIN;
            storage.setRole(global.roles.ADMIN);
            setCurrentRoutes(global.roles.ADMIN);
            // role.value = global.roles.USER;
            // storage.setRole(global.roles.USER);
            // setCurrentRoutes(global.roles.USER);
          }
          // 假的role
          // role.value = global.roles.SUPER;
          // storage.setRole(global.roles.SUPER);
          // setCurrentRoutes(global.roles.SUPER); 
          storage.setUserInfo(JSON.stringify(user));
          storage.setUserId(user.userId);
          storage.setModal(modalCode);
          storage.setModalTitle(modalTitle);
          // console.log('resolve')
          resolve(user);
        })
        .catch(err => {
          reject(err.message || '获取用户信息失败，请稍后重试');
        });
    });
  }

  function logout(){
    return new Promise((resolve, reject) => {
      try {
        token.value = null;
        userId.value = null;
        userInfo.value = null;
        role.value = null;
        currentRoutes.value = '';
        currentModal.value = null;
        storage.removeToken();
        storage.removeUserId();
        storage.removeUserInfo();
        storage.removeRole();
        storage.removeRoutes();
        storage.removeModal();
        storage.removeModalTitle();
        Router.default.clearRoutes();
        Router.constantRoutes.forEach(r => Router.default.addRoute(r));
        resolve();
      } catch (err){
        reject(err)
      }
      
    });
  }
  // 根据角色获取筛选过的路由
  function getDynamicRoutes(roles){
    let currentRole = roles.split(',');
    let dynamicRoutes = deepCopy(Router.dynamicRoutes);
    if (currentRole.includes(status.global.roles.SUPER) || currentRole.includes(status.global.roles.ADMIN)){
      return fliterRouter(dynamicRoutes, status.global.roles.ADMIN);
    } else if (currentRole.includes(status.global.roles.DEVELOPER)) {
      return fliterRouter(dynamicRoutes, status.global.roles.DEVELOPER);
    } else if (currentRole.includes(status.global.roles.USER)) {
      return fliterRouter(dynamicRoutes, status.global.roles.USER);
    }
    // 重构路由方法
    function fliterRouter(routers, rol){
      const routerArr = [];
      routers.forEach(r => {
        if (r.meta && r.meta.role && r.meta.role.includes(rol)){
          routerArr.push(r);
        }
        if (r.children && r.children.length > 0){
          r.children = fliterRouter(r.children, rol);
        }
      });
      return routerArr;
    }
  }
  // 根据角色设置pinia和storage的当前路由
  function setCurrentRoutes(currentRole){
    const appStore = useAppStore();
    let routes = getDynamicRoutes(currentRole);
    // 动态添加过滤后的路由
    routes.forEach(r => Router.default.addRoute(r));
    // let algorithmCreateRouter = {
    //   path: '/algorithmCreate',
    //   name: 'algorithmCreate',
    //   meta: { 
    //     show: true, 
    //     icon: 'icon-newdocumentworksheet', 
    //     isLink: true, 
    //     title: '生成算法', 
    //     exclude: true,
    //     role: [  '3' ]
    //   },
    //   component: null
    // };
    // switch (currentModal.value){
    //   case 'image':
    //     algorithmCreateRouter.component = () => import('@/views/algorithm/image/algorithmCreate.vue');
    //     // algorithmCreateRouter.component = () => import('@/views/algorithm/image/algorithmCreateTable.vue');
    //     break;
    //   case 'video':
    //     algorithmCreateRouter.component = () => import('@/views/algorithm/video/algorithmCreate.vue');
    //     break;
    //   case 'audio':
    //     algorithmCreateRouter.component = () => import('@/views/algorithm/voice/algorithmCreate.vue');
    //     break;
    // }
    // Router.default.addRoute('algorithm', algorithmCreateRouter);
    // Router.default.addRoute()
    currentRoutes.value = routes;
    storage.setRoutes(JSON.stringify(routes));
    appStore.changeIsAddRoutes(true);
  }
  // 暴露出修改当前路由的方法
  function changeCurrentRoutes(routes){
    currentRoutes.value = routes;
    storage.setRoutes(JSON.stringify(routes));
  }

  // 修改当前模态
  function changeCurrentModal(modal){
    currentRoutes.value = modal;
    storage.setModal(modal);
  }
  function changeCurrentModalTitle(title){
    currentModalTitle.value = title;
    storage.setModalTitle(title);
  }

  return {
    token,
    userId,
    userInfo,
    role,
    isLogin,
    currentRoutes,
    currentModal,
    currentModalTitle,
    login,
    getCurrentUserInfo,
    setCurrentRoutes,
    changeCurrentRoutes,
    changeCurrentModal,
    changeCurrentModalTitle,
    logout
  };
});

export default useUserStore;